<?php
class MessagesController extends AppController 
{
	var $name = 'Messages';

    function index()
    {
        $this->set('shoutbox', $this->Message->getData());
        $this->set('module', 'message');
    }

	function add()
	{
		if(!empty($this->data))
		{
			//add ipaddress to data
			$this->data['Message']['ipaddress'] = $_SERVER['REMOTE_ADDR'];
			
			//maak de info schoon
			App::import('Core', 'Sanitize');
			$this->data['Message']['body'] = Sanitize::html($this->data['Message']['body']);
			$this->data['Message']['name'] = Sanitize::html($this->data['Message']['name']);
			
			$this->data['Message']['website'] = ($this->data['Message']['website'] == "http://") ? "" : Sanitize::html($this->data['Message']['website']);

			if ($this->Message->save($this->data))
			{
				$this->Session->setFlash('Bericht toegevoegd.');
				
				$mailBody  = "Naam: {$this->data['Message']['name']}\r\n";
				$mailBody .= "Website: {$this->data['Message']['website']}\r\n";
				$mailBody .= "Bericht: {$this->data['Message']['body']}\r\n\r\n";
				$mailBody .= "http://www.rugbyclubdwingeloo.nl/messages/activate/{$this->Message->id}\r\n\r\n";
				$mailBody .= "http://www.rugbyclubdwingeloo.nl/messages/delete/{$this->Message->id}\r\n";
				
				$headers  = "MIME-Version: 1.0 \r\n";
				$headers .= "Content-Type: text/plain; charset=\"utf-8\" \r\n";
				$headers .= "From: {$this->data['Message']['name']}" . "\r\n";

				mail(
					"geert1@gmail.com",
					"Gastenboek bericht",
					$mailBody,
					$headers
				);

				//$this->redirect('/');
                echo $_SESSION['shoutbox'];
			} else
			{
				$this->Session->setFlash('Er is iets fout gegaan.');
                echo $_SESSION['shoutbox'];
				//$this->redirect('/');
				//$this->Session->write('Message.errors', $this->Message->invalidFields());
				//$this->redirect($this->referer());
			}
		}
	}
	
	function activate()
	{
		$id = $this->params['pass'][0];
		$this->Message->id = $id;
		$data['Message']['active'] = 1;
		$this->Message->save($data);
		$this->redirect('/');
	}
	
	function delete()
	{
		$id = $this->params['pass'][0];
		$ip = $this->Message->find('first', array(
			'fields' => 'ipaddress',
			'conditions' => 'id = ' . $id,
		));
		$ban['Ban']['ipaddress'] = $ip['Message']['ipaddress'];
		$ban['Ban']['reason'] = "shoutbox";
		
		$this->loadModel("Ban");
		
		$this->Message->delete($id);
		$this->Ban->save($ban);
	}
}
?>
